import { ElMessage } from 'element-plus'
import cartItemApi from '../../api/cartItem'
import { getMyCart, removeMyCart, setMyCart } from '../../utils/auth'

const cart = {
  state: {
    cartList: getMyCart() // 加入购物车列表
  },
  mutations: {
    // 加入购物车
    ADD_CART (state, product) {
      let flag = true
      let cartList = state.cartList
      if (cartList.length) {
        cartList.forEach(e => {
          if (e.id === product.id) {
            flag = false
          }
        })
      }
      if (!cartList.length || flag) {
        product.checked = true
        cartList.push(product)
      }
      state.cartList = cartList
      setMyCart(state.cartList)
      console.log('购物车容量:', state.cartList.length)
    },
    // 从购物车移除
    REMOVE_CART (state, product) {
      let cartList = state.cartList
      // 先移除 再重新加入
      if (product.id) {
        cartList.splice(cartList.findIndex(e => e.id === product.id), 1)
        ElMessage.success(`'${product.name}'移出购物车成功`)
      }
      state.cartList = cartList
      setMyCart(state.cartList)
    },
    // 设置选中状态
    CHANGE_CHECKED (state, { productId, checked = true }) {
      let cartList = state.cartList
      if (productId) {
        cartList.forEach(e => {
          if (e.id === productId) {
            e.checked = checked
          }
        })
      }
      setMyCart(state.cartList)
    },
    // 清空购物车
    REMOVE_CART_ALL (state) {
      state.cartList = []
      setMyCart(state.cartList)
      removeMyCart()
    },
  },
  actions: {
    // 获取购物车商品
    GetCartProducts ({ commit, state }) {
      return new Promise(((resolve, reject) => {
        let cartList = []
        cartItemApi.getCartProducts().then(res => {
          let products = res.data
          products.forEach(item => {
            item.checked = true
            cartList.push(item)
          })
          state.cartList = cartList
          setMyCart(state.cartList)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      }))
    }
  }
}

export default cart
